import axios from "axios";
import {getCookie, removeCookie} from '@/utils/auth'
import {Notification, MessageBox, Message} from "element-ui";

import qs from "qs";
//引入路由
import router from "../router";
import store from "../store";
// axios.defaults.withCredentials = true;
axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded";
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: window.MyUrl.BaseUrl,
  // 超时
  // timeout: 10000,
});

// request拦截器
service.interceptors.request.use((config) => {
  if (config.method != 'delete' && config.method != 'put' && config.datat !== 'json' && config.datat !== 'form') {
    config.data = qs.stringify(config.data);
  }
  let token = getCookie("token");
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  if (token && !isToken) {
    config.headers["Authorization"] = "Bearer " + token; // 让每个请求携带自定义token 请根据实际情况自行修改
    config.headers.token = token
  }
  return config;
});

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    let {code, msg} = res.data
    if (code === 0) {
      return res
    } else if (code === 1) {
      Message.error(msg)
      return Promise.reject(res.data)
    } else if (code == 2) {
      removeCookie();
      store.dispatch('permission/resetRoutes', null)
      router.push({name: 'login'})
      return res
    } else {
      return Promise.reject(res.data)
    }
  },
  error => {
    switch (error.response.status) {
      case 500:
        if (error.response.data.code === 2) {
          removeCookie();
          store.dispatch('permission/resetRoutes', null)
          router.replace({name: 'login'})
        }
      default:
        console.log(1)
    }

    return Promise.reject(error)
  }
)

export default service;
